package com.alertdroid2;

import java.io.IOException;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

public class alertdroid2 extends ListActivity {
	DatabaseHelper myDbHelper;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		try {
			initDb();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		refreshMemo();
	}

	public void refreshMemo() {
		ArrayList<MemoClass> memoClass = myDbHelper.getAllMemo();

		final ListView lv1 = (ListView) findViewById(android.R.id.list);
		lv1.setAdapter(new MyCustomBaseAdapter(this, memoClass));
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		refreshMemo();
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		myDbHelper.closeDb();
		super.onDestroy();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		ArrayList<MemoClass> memoClass = myDbHelper.getAllMemo();
		int idMemo = memoClass.get(position).idMemo;

		Intent i = new Intent(getBaseContext(), viewMemoActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		i.putExtra(alertdroidConstants.IDMEMO, idMemo);

		startActivity(i);

		super.onListItemClick(l, v, position, id);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.setQwertyMode(true);
		MenuItem mnu1 = menu.add(0, 0, 0, "Add Memo");
		{
			mnu1.setAlphabeticShortcut('a');
			// mnu1.setIcon(R.drawable.alert_dialog_icon);
		}
		MenuItem mnu2 = menu.add(0, 1, 1, "Add Place");
		{
			mnu2.setAlphabeticShortcut('b');
		}
		MenuItem mnu3 = menu.add(0, 2, 2, "Refresh");
		{
			mnu3.setAlphabeticShortcut('c');
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case 0:
			startActivity(new Intent(this, addMemoActivity.class));
			return true;
		case 1:

			return true;
		case 2:
			refreshMemo();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	private void initDb() throws IOException {
		myDbHelper = new DatabaseHelper(this);
		myDbHelper.createDataBase();
		try {
			myDbHelper.openDataBase();
		} catch (SQLException sqle) {
			throw sqle;
		}
	}
}